import JEditableTable from '@/components/jeecg/JEditableTable'
import { VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { httpAction, getAction } from '@/api/manage'
import { getLanCode } from '@/lang'
import { showPurchase,getCurrentSystemConfig } from '@/api/api'
import { randomUUID} from '@/utils/util'
import moment from 'moment';
import pick from 'lodash.pick'
import Vue from 'vue';
export const JEditableTableMixin = {
  provide(){
    return {
      getFileList: ()=>{
        return {filelist : this.filelist}
      },
      setLoading: ()=>{
        this.submitBtnDisabled = true
        return true
      },
      getLoading: ()=>{
        return this.submitBtnDisabled
      }
    }
  },
  components: {
    JEditableTable
  },
  data () {
    return {
      title: getLanCode() === 'zh' ? '操作' : 'Operation',
      visible: false,
      form: this.$form.createForm(this),
      confirmLoading: false,
      model: {},
      queryParams: {},
      materialTable: {},
      btnEnableList:'',
      showRecover:false,//显示恢复缓存
      handleTime:null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
  },
  methods: {
    /** 获取所有的editableTable实例 */
    getAllTable () {
      if (!(this.refKeys instanceof Array)) {
        throw this.throwNotArray('refKeys')
      }
      let values = this.refKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    /** 遍历所有的JEditableTable实例 */
    eachAllTable (callback) {
      // 开始遍历
      this.getAllTable().then(tables => {
        
        tables.forEach((item, index) => {
          if (typeof callback === 'function') {
            callback(item, index)
          }
        })
      })
    },

    /** 当点击新增按钮时调用此方法 */
    add () {
      this.addInit()
      if (typeof this.addBefore === 'function') this.addBefore()
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      console.log('handler: add');
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn(
          '由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0'
        )
      }
      this.eachAllTable(item => {
        item.add(rowNum)
      })
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
      this.edit({})
    },
    /** 当点击了编辑（修改）按钮时调用此方法 */
    edit (record) {
      // 判断新增\编辑-显示原数量、原金额
      this.showOriginalQuantity(record)
      console.log('handler: edit, @param{}record', record);
      // 根据权限-修改(操作金额)显示内容
      this.showPurchase()
      // this.
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.onPlusKey()
      if (typeof this.fileItemList === 'function') this.fileItemList(this.model)
      // 获取modal缓存
      const userName = this.getLocalStorage('pro__Login_Userinfo').loginName
      const storage = Vue.ls.get('_unsave_modal_cache_' + userName +'_'+ this.prefixNo)
      console.log('object :>> ', '_unsave_modal_cache_' + userName +'_'+ this.prefixNo);
      console.log('storage :>> ', storage);
      this.showRecover = !!storage
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    
    onPlusKey() { // 监听键盘
      document.onkeydown = (e)=> {            
        let key = window.event.keyCode; 
        // +键触发新增行
        if(key === 107 && this.visible){
          this.$refs[this.refKeys[0]].handleClickAdd()
        }
      }
    },
    showPurchase () {
      var _this = this
      _this.materialTable.loading = true
      showPurchase().then(res => {
        console.log('handler: showPurchase, res:', res)
        console.log('handler: prefixNo', this.prefixNo)
      _this.materialTable.loading = false
      // 仅仅限制采购订单里面的采购价
      let prefixNoArr = ['CGDD','CJBJ','CGRK']
        if (res === false && prefixNoArr.includes(this.prefixNo)) {
          // 隐藏
          this.showPrice = false
          let hiddenColumns = 'unitPrice,allPrice,taxRate,taxMoney,taxUnitPrice,taxLastMoney'
          for (var key in _this.materialTable.columns) {
            if (hiddenColumns.includes(_this.materialTable.columns[key].key)) {
              this.changeFormTypes(this.materialTable.columns, _this.materialTable.columns[key].key, 0)
            }
          }
        }
      })
    },
    showOriginalQuantity (record) {
      if (record) {
        if (record.quotationStatus == 0) {
          for (var key in this.materialTable.columns) {
            this.changeFormTypes(this.materialTable.columns, 'custom6', 0)
            this.changeFormTypes(this.materialTable.columns, 'custom7', 0)
          }
        } else if (record.quotationStatus == 1) {
          for (var key in this.materialTable.columns) {
            this.changeFormTypes(this.materialTable.columns, 'custom6', 1)
            this.changeFormTypes(this.materialTable.columns, 'custom7', 1)
          }
        }
      }
      // if (record.custom6 == undefined) {
      //   console.log('进入record.custom6')
      //   for (var key in this.materialTable.columns) {
      //     if (this.materialTable.columns[key].key === 'custom6') {
      //       this.materialTable.columns.splice(key, 2)
      //     }
      //   }
      // }
    },
    /** 关闭弹窗，并将所有JEditableTable实例回归到初始状态 */
    close () {
      this.visible = false
      this.eachAllTable(item => {
        item.initialize()
      })
      // 清除文件
      localStorage.removeItem('fileList')
      localStorage.removeItem('fileListId')
      document.onkeyup = null
      this.$emit('close')
    },

    /** 查询某个tab的数据 */
    requestSubTableData (url, params, tab, success) {
      if(typeof(tab.loading)!="undefined" && typeof(tab.loading)!="null") {
        tab.loading = true
      }
      getAction(url, params)
        .then(res => {
          if (res && res.code === 200) {
            tab.dataSource = res.data.rows
            typeof success === 'function' ? success(res) : ''
          }
        })
        .finally(() => {
          tab.loading = false
        })
    },
    
    // 后端接口传回的数据不同，跟上面共用不了，按里来说后端要传回共用的
    /** 查询某个tab的数据 */
    requestSubTableData1 (url, params, tab, success) {
      tab.loading = true
      getAction(url, params)
        .then(res => {
          if (res && res.code === 200) {
            res.data.meList.forEach(item => {
              item.name = item.materialName
            })
            tab.dataSource = res.data.meList
            typeof success === 'function' ? success(res) : ''
          }
        })
        .finally(() => {
          tab.loading = false
        })
    },
    /** 查询某个tab的数据 */
    requestSubTableData2 (url, params, tab, success) {
      tab.loading = true
      getAction(url, params)
        .then(res => {
          if (res && res.code === 200) {
            let arr = []
            let brr = []
            res.data.rows.forEach(item => {
              arr.push(...item.promotionGiftList)
            })
            arr = [...arr]
            // console.log('arr')
            // console.log(arr)
            // let a = [...arr[0], ...arr[1]]
            arr.forEach(item => {
              item.barCode = item.giftBarCode
              // item.giftMeId = item.meId
              // item.materialId = item.itemId
              item.meId = item.itemId
              if (this.materialTable.dataSource[0].id == item.meId) {
                // console.log('item1')
                // console.log(item)
                brr.push(item)
              }
            })
            tab.dataSource = brr
            this.shopIdList = arr
            for (let i = 0; i < tab.dataSource.length; i++) {
              let info = tab.dataSource[i]
              this.changeColumnShow(info)
            }
            typeof success === 'function' ? success(res) : ''
          }
        })
        .finally(() => {
          tab.loading = false
        })
    },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    request (formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      if(this.submitBtnDisabled !== undefined) this.submitBtnDisabled = true
      httpAction(url, formData, method)
        .then(res => {
          if (res.code === 200) {
            this.$emit('ok')
            this.confirmLoading = false
            if(this.clearData && typeof this.clearData === 'function')  this.clearData()
            this.close()
          } else {
            this.$message.warning(res.data.message || res.data)
            this.confirmLoading = false
          }
          if(this.submitBtnDisabled !== undefined) this.submitBtnDisabled = false
        })
        .finally(() => {})
        .catch(e=>{
          if(this.submitBtnDisabled !== undefined) this.submitBtnDisabled = false
          this.confirmLoading = false
        })
    },

    /* --- handle 事件 --- */

    /** ATab 选项卡切换事件 */
    handleChangeTabs (key) {
      // 自动重置scrollTop状态，防止出现白屏
      getRefPromise(this, key).then(editableTable => {
        editableTable.resetScrollTop()
      })
    },
    
    /* 按钮权限 */
    initActiveBtnStr () {
      let btnStrList = Vue.ls.get('winBtnStrList') //按钮功能列表 JSON字符串
      this.btnEnableList = '' //按钮列表
      let pathName = location.pathname
      if (pathName.indexOf('/plugins') > -1) {
        pathName = '/system' + pathName
      }
      if (pathName && btnStrList) {
        for (let i = 0; i < btnStrList.length; i++) {
          if (btnStrList[i].url === pathName) {
            if (btnStrList[i].btnStr) {
              this.btnEnableList = btnStrList[i].btnStr
            }
          }
        }
      }
    },
    /** 关闭按钮点击事件 */
    handleCancel() {
      // 缓存未保存的table数据
      if(!this.model.id){
        //新增模式才缓存
        this.setUnsaveToLocalStorage()
      }
      if(this.clearData && typeof this.clearData === 'function')  this.clearData()
      this.close()
    },
    
    // 获取localStorage数据
    getLocalStorage (key) {
      var value = localStorage.getItem(key) // 取回 value 变量
      this.localStorageKeyJson = JSON.parse(value)
      return this.localStorageKeyJson.value
    },
    // 恢复
    recover(){
      const userName = this.getLocalStorage('pro__Login_Userinfo').loginName
      let storage = Vue.ls.get('_unsave_modal_cache_' + userName +'_' + this.prefixNo)
      if(storage){
        this.model = Object.assign(this.model,storage.form)
        if(this.materialTable){
          this.materialTable.dataSource = storage.dataSource
        }
        if(this.accountTable){
          this.accountTable.dataSource = storage.dataSource
        }
        localStorage.setItem('fileList', JSON.stringify(storage.fileList))
        this.fileList = (storage.fileList || []).map(v=>{
          return  {
            uid :randomUUID(),
            url :v.data,
            flag :'1',
            status :'done',
            name :v.fileName,
            data:v.data,
            type:v.type
          }
        })
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,...Object.keys(this.model)))
        });
      }
      this.showRecover = false
    },
    lose(){
      const userName = this.getLocalStorage('pro__Login_Userinfo').loginName
      Vue.ls.remove('_unsave_modal_cache_' + userName +'_' + this.prefixNo)
      this.showRecover = false
    },
    // 缓存未保存的table数据
    setUnsaveToLocalStorage(){
      const fileList = JSON.parse(localStorage.getItem("fileList"))
      const userName = this.getLocalStorage('pro__Login_Userinfo').loginName
      this.getAllTable()
        .then(tables => {
          tables[0].getAll(false,true).then(res=>{
            console.log('6665 :>> ', 6665);
            let form = this.form.getFieldsValue()
            const {operTime,number,creator,billTime,billNo,...newForm} = form
            let arr = Object.values(newForm)
            arr = arr.filter(v=>v)
            console.log('arr :>> ', arr);
            console.log('res.values :>> ', res.values);
            console.log('fileList :>> ', fileList);
            if(arr.length || res.values.length || (fileList && fileList.length)){
              console.log('开始缓存 :>> ');
              let storage = {
                form:newForm,
                dataSource:res.values,
                fileList: fileList || []
              }
              Vue.ls.set('_unsave_modal_cache_' + userName +'_' +this.prefixNo,storage) 
            }
          })
        })
    },
    onDateCXTJChange (value, dateString) {
      this.queryParams.startTime = dateString[0] + ' 00:00:00' 
      this.queryParams.endTime = dateString[1] + ' 23:59:59' 
      console.log('this.queryParams :>> ', this.queryParams);
    },
    handleFincialOk(){
      validateFormAndTables(this.form).then(allValues =>{
      })
    },
    /** 确定按钮点击事件 */
    handleCXTJOk (promotionType) {
      /** 触发表单验证 */
      this.getAllTable()
        .then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        })
        .then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          // let arr = {
          //   // 促销类型  1-直接特价
          //   promotionType: 1,
          //   promotionName: allValues.formValue.promotionName,
          //   holdSupplier: allValues.formValue.holdSupplier,
          //   holdDepot: allValues.formValue.holdDepot,
          //   promotionNo: allValues.formValue.promotionNo,
          //   endTime: this.queryParams.endTime,
          //   startTime: this.queryParams.startTime,
          //   person: allValues.formValue.person,
          //   meList: allValues.tablesValue
          // }
          let formData = this.classifyIntoFormData(allValues)
          console.log(formData,999)
          let arr = {}
          let brr = {}
          // let listArr = []
          arr = JSON.parse(JSON.stringify(formData.info))
          // brr = JSON.parse(JSON.stringify(formData.rows))
          arr = JSON.parse(arr)
          // brr = JSON.parse(brr)
          arr.promotionType = promotionType //促销类型  1-直接特价  2-买满金额减金额  3-买满数量送赠品
          console.log('this.queryParams :>> ', this.queryParams);
          arr.startTime = moment(arr.createTimeRange[0]).format('YYYY-MM-DD') + ' 00:00:00'
          arr.endTime = moment(arr.createTimeRange[1]).format('YYYY-MM-DD') + ' 23:59:59'


          // let materialId = localStorage.getItem('materialIds')
          // materialId = materialId.split(',')
          allValues.tablesValue[0].values.forEach((item, index) => {
            item.materialName = item.name
            // item.materialId = materialId[index]
            item.commodityUnit = item.unit
          })
          // 拼接赠品数据
          let mainSource = this.materialTable.dataSource
          let shopIdList = []
          mainSource.forEach(val => {
            if (val.shopIdList && val.shopIdList.length) {
              val.shopIdList.forEach(v => {
                let obj = {
                  giftMaterialId: v.giftMaterialId,
                  giftMeId: v.meId || v.giftMeId,
                  giftQuantity: v.giftQuantity, 
                  id: v.id,
                  materialId: val.materialId,
                  meId: val.meId,
                  name: v.name,
                  standard: v.standard,
                  giftMaterialUnit: v.unit
                }
                shopIdList.push(obj)
              })
            }
          })
          arr.meList = allValues.tablesValue[0].values
          arr.promotionGiftList =  shopIdList
          arr.depotList = []
          return this.request(arr)
        })
        .catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
    },
    /** 确定按钮点击事件 */
    handleMJJEOk () {
      /** 触发表单验证 */
      this.getAllTable()
        .then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        })
        .then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          console.log(allValues)
          let arr = {}
          let brr = {}
          arr = JSON.parse(JSON.stringify(formData.info))
          brr = JSON.parse(JSON.stringify(formData.rows))
          arr = JSON.parse(arr)
          brr = JSON.parse(brr)
          arr.startTime = arr.createTimeRange[0]
          arr.endTime = arr.createTimeRange[1]
          arr.promotionType = 1 // 促销类型  1-直接特价
          brr.forEach(item => {
            item.materialId = item.id
            item.commodityUnit = item.unit
          })
          arr.meList = brr
          arr.depotList = []
          arr.supplierList = []
          console.log(arr)
          // 发起请求
          return this.request(arr)
        })
        .catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
    },
    /** 确定按钮点击事件 */
    handleReleasePurchaseOk() {
      

      /** 触发表单验证 */
      this.getAllTable()
        .then(tables => {
          /** 一次性验证主表和所有的次表 */
          console.log(tables,6666);
          return validateFormAndTables(this.form, tables)
        })
        .then(allValues => {
          allValues.tablesValue[0].values.forEach((item, index) => {
            if (this.materialTable.dataSource[index].organName !== null) {
              console.log(this.materialTable.dataSource[index].organId)
              item.organId = this.materialTable.dataSource[index].organId
              item.organName = this.materialTable.dataSource[index].organId
              console.log(item.organId)
            }
            item.organId = item.organName
            // console.log(allValues.tablesValue[0].values[index])
          })
          // console.log(allValues.tablesValue[0].values)
          // console.log(this.materialTable.dataSource)
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          console.log(formData);
          formData.passDirect = true
          formData.functionId = '261'
          formData.id = this.selectionRows
          // 发起请求
          return this.requestReleasePurchase(formData)
        })
        .catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
    },
    requestReleasePurchase (formData) {
      this.confirmLoading = true
      httpAction('/depotHead/issuePurchase', formData, 'post')
        .then(res => {
          if (res.code === 200) {
            this.$emit('ok')
            this.confirmLoading = false
            this.close()
          } else {
            this.$message.warning(res.data.message)
            this.confirmLoading = false
          }
        })
        .finally(() => {})
    },
    /**
     * 
     * @param {*} handleOk 
     * @param {*} delay 延迟
     * @returns 
     * 对提交方法防抖处理
     */
     handleOk() {
        if (this.handleTime !== null) {
          clearTimeout(this.handleTime);
        }
        this.handleTime = setTimeout(() => {
            this.handleSubmit()
        }, 500)
    },
    /** 确定按钮点击事件 */
    handleSubmit () {
      /** 触发表单验证 */
      this.getAllTable()
        .then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        })
        .then(async allValues => {
          
          if(typeof(this.submitBtnDisabled)!="undefined"){
            this.submitBtnDisabled = true
          }
          let checkoutFlag = false
          
          this.confirmLoading = true
          // console.log('this.materialTable.dataSource')
          // console.log(this.materialTable.dataSource)
          if (this.$route.name == '验收单' || this.$route.name == '配送单') {
            // allValues.tablesValue[0].values.forEach(item => {
            //   if (item.preNumber == '') {
            //     checkoutFlag = true
            //     return this.$message.warning('请通过选择源单录入数据')
            //   }
            // })
            allValues.formValue.linkNumber = allValues.formValue.number
          }
          if (this.$route.name == '组装单' || this.$route.name == '拆卸单') {
            allValues.tablesValue[0].values.forEach((item, index) => {
              if (allValues.tablesValue[0].values[0].color !== item.color) {
                checkoutFlag = true
                return this.$message.error('第' + (index + 1) + '行关联码与第一行不相同，不能拆卸或组装')
              }
            })
          }
          // 检查是否设置了公司前缀
          const sysConfig = await getCurrentSystemConfig()
          if(!sysConfig || sysConfig.code !== 200 || !sysConfig.data ||!sysConfig.data.companyPostCode ){
            this.$message.error(this.$t('otherJS.yetSetPrefixCanot'))
            throw new Error(this.$t('otherJS.yetSetPrefixCanot'))
          }
          // 运费单
          
          if (checkoutFlag == true) {
            return false
          }
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          if(formData.attachment && formData.attachment.length){
            let attachment
            try {
              attachment = JSON.parse(formData.attachment)
              let fileNames = []
              if(attachment && attachment.length){
                attachment.forEach(v=>{
                  fileNames.push(v.fileName)
                })
                let info = JSON.parse(formData.info)
                info.fileName = fileNames.join(',')
                formData.info = JSON.stringify(info)
              }
            } catch (err) {
              console.log(err,222);
            }
          }else{
            delete formData.attachment
          }
          console.log('formData',formData);
          formData.passDirect = true
          formData.functionId = this.$route.meta.id
          console.log(999,formData)
          // 发起请求 
          return this.request(formData)
        })
        .catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
    },
    /* --- throw --- */

    /** not a function */
    throwNotFunction (name) {
      return `${name} 未定义或不是一个函数`
    },

    /** not a array */
    throwNotArray (name) {
      return `${name} 未定义或不是一个数组`
    }
  }
}
